package top.lishuoboy.javaweb.a07servlet;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

/**
 * http://localhost:8080/lishuoboy_javaweb_war_exploded/A02Servlet?name=硕&hobby=吃&hobby=喝&hobby2=嫖&hobby2=赌
 *
 * @author lishuoboy
 * @date 2022-01-05 11:41
 */
@Slf4j
@WebServlet(name = "A02Servlet", value = "/A02Servlet", initParams = {@WebInitParam(name = "myParam", value = "servlet初始参数")})
public class A02Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        log.warn("==请求转发====================================");
//        request.getRequestDispatcher("/A01Servlet").forward(request,response); //请求转发

        log.warn("==字符集信息====================================");
        log.info("{}", request.getCharacterEncoding());  // UTF-8

        log.warn("==客户端信息====================================");
        log.info("{}", request.getRemoteAddr());     // 192.168.0.106
        log.info("{}", request.getRemoteHost());     // 192.168.0.106
        log.info("{}", request.getRemotePort());     // 44450
        log.info("{}", request.getRemoteUser());     // null

        log.warn("==本地信息====================================");
        log.info("{}", request.getLocalAddr());      // 192.168.0.110
        log.info("{}", request.getLocalName());      // lishuoboy-PC
        log.info("{}", request.getLocalPort());      // 8080

        log.warn("==请求行信息====================================");
        log.info("{}", request.getMethod());         // GET
        log.info("{}", request.getProtocol());       // HTTP/1.1
        log.info("{}", request.getRequestURL());     // http://192.168.0.110:8080/lishuoboy_javaweb_war_exploded/A02Servlet
        log.info("{}", request.getScheme());         // http
        log.info("{}", request.getServerName());     // 192.168.0.110/localhost/127.0.0.1
        log.info("{}", request.getServerPort());     // 8080
        log.info("{}", request.getRequestURI());     // /lishuoboy_javaweb_war_exploded/A02Servlet
        log.info("{}", request.getContextPath());    // /lishuoboy_javaweb_war_exploded
        log.info("{}", request.getServletPath());    // /A02Servlet
        log.info("{}", request.getQueryString());    // get才有 name=硕&hobby=吃&hobby=喝&hobby2=嫖&hobby2=赌

        log.warn("==请求头信息====================================");
//        host==192.168.0.110:8080, request.getHeaders==[192.168.0.110:8080]
//        connection==keep-alive, request.getHeaders==[keep-alive]
//        content-length==80, request.getHeaders==[80]
//        cache-control==max-age=0, request.getHeaders==[max-age=0]
//        upgrade-insecure-requests==1, request.getHeaders==[1]
//        origin==http://192.168.0.110:8080, request.getHeaders==[http://192.168.0.110:8080]
//        content-type==application/x-www-form-urlencoded, request.getHeaders==[application/x-www-form-urlencoded]
//        user-agent==Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62, request.getHeaders==[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62]
//        accept==text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9, request.getHeaders==[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9]
//        referer==http://192.168.0.110:8080/lishuoboy_javaweb_war_exploded/07servlet/request.html, request.getHeaders==[http://192.168.0.110:8080/lishuoboy_javaweb_war_exploded/07servlet/request.html]
//        accept-encoding==gzip, deflate, request.getHeaders==[gzip, deflate]
//        accept-language==zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6, request.getHeaders==[zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6]
//        cookie==JSESSIONID=64E64DB5FA33A5465C496C3F98B94985, request.getHeaders==[JSESSIONID=64E64DB5FA33A5465C496C3F98B94985]
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info("{}=={}, request.getHeaders=={}", headerName, request.getHeader(headerName), ListUtil.list(false, request.getHeaders(headerName)));
        }

        log.warn("==请求体信息====================================");
        log.info("{}", request.getContentType());        // post才有  application/x-www-form-urlencoded
        log.info("{}", request.getContentLength());      // post才有  80
        log.info("{}", request.getContentLengthLong());  // post才有  -1
//        log.info("{}", IoUtil.read(request.getReader(),false));
        // 对于post请求，获取流与获取参数只能获取一次，后获取的就没数据了，先注释掉
        log.info("{}", IoUtil.read(request.getInputStream(), StandardCharsets.UTF_8));  // post才有  name=硕&hobby=吃&hobby=喝&hobby2=嫖&hobby2=赌

        log.warn("==请求参数信息1====================================");
        // 对于post请求，获取流与获取参数只能获取一次，后获取的就没数据了
        // name==硕, name==[硕]
        // hobby==吃, hobby==[吃, 喝]
        // hobby2==嫖, hobby2==[嫖, 赌]
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            log.info("{}=={}, {}=={}", paramName, request.getParameter(paramName), paramName, request.getParameterValues(paramName));
        }

        log.warn("==请求参数信息2====================================");
        // 对于post请求，获取流与获取参数只能获取一次，后获取的就没数据了
        // name==[硕]
        // hobby==[吃, 喝]
        // hobby2==[嫖, 赌]
        Map<String, String[]> paramMap = request.getParameterMap();
        for (Map.Entry<String, String[]> strEntry : paramMap.entrySet()) {
            log.info("{}=={}", strEntry.getKey(), strEntry.getValue());
        }

        log.warn("==cookie 信息====================================");
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            log.info("cookies[{}]=={}", i, BeanUtil.beanToMap(cookies[i]));  // cookies[0]=={name=JSESSIONID, value=75337EA92CF966565E6E6B822F8F6C02, version=0, comment=null, domain=null, maxAge=-1, path=null, secure=false, httpOnly=false}
        }

        log.warn("==属性（四个作用域之一）信息====================================");
        Enumeration<String> attributeNames = request.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String attributeName = attributeNames.nextElement();
            log.info("attributeName=={}, request.getAttribute=={}", attributeName, StrUtil.removeAll(String.valueOf(request.getAttribute(attributeName)), StrPool.LF));
        }

        log.warn("==地区信息====================================");
        log.info("{}", request.getLocale());    // zh_CN
        Enumeration<Locale> locales = request.getLocales();
        log.info("{}", ListUtil.list(false, locales));  // [zh_CN, zh, en, en_GB, en_US]

        log.warn("==其它信息====================================");
        log.info("{}", request.getAuthType());                  // null
        log.info("{}", request.getPathInfo());                  // null
        log.info("{}", request.getPathTranslated());            // null
        log.info("{}", request.getTrailerFields());             // {}
//        log.info("{}", request.getAsyncContext());
        log.info("{}", BeanUtil.beanToMap(request.getHttpServletMapping())); // {matchValue=A02Servlet, pattern=/A02Servlet, servletName=A02Servlet}

        // session
        log.warn("==session 信息====================================");
        HttpSession session = request.getSession();
        log.info("{}", session.getId());                        // 982532BDEC32B4D69EDED315405600AB
        log.info("{}", session.getCreationTime());              // 1641378245676
        log.info("{}", session.getLastAccessedTime());          // 1641378245676
        log.info("{}s", session.getMaxInactiveInterval());      // 1800s

        log.warn("==session 属性（四个作用域之一）信息====================================");
        Enumeration<String> sessionAttributeNames = session.getAttributeNames();
        while (sessionAttributeNames.hasMoreElements()) {
            String sAttributeName = sessionAttributeNames.nextElement();
            log.info("{}=={}", sAttributeName, session.getAttribute(sAttributeName));
        }

        // ServletContext
        ServletContext context = session.getServletContext();
        log.warn("==context 信息====================================");
        log.info("{}", context.getResource(""));                                 // file:/D:/workspace/lishuoboy-javaweb/target/lishuoboy-javaweb-1.0-SNAPSHOT/
        log.info("{}", context.getResource("/WEB-INF/classes/logback-test.xml"));// file:/D:/workspace/lishuoboy-javaweb/target/lishuoboy-javaweb-1.0-SNAPSHOT/WEB-INF/classes/logback-test.xml
        log.info("{}", context.getRealPath(""));                                 //       D:\workspace\lishuoboy-javaweb\target\lishuoboy-javaweb-1.0-SNAPSHOT\
        log.info("{}", context.getRealPath("WEB-INF/classes/logback-test.xml")); //       D:\workspace\lishuoboy-javaweb\target\lishuoboy-javaweb-1.0-SNAPSHOT\WEB-INF\classes\logback-test.xml
        log.info("{}", context.getRealPath("/WEB-INF/classes/logback-test.xml"));//       D:\workspace\lishuoboy-javaweb\target\lishuoboy-javaweb-1.0-SNAPSHOT\WEB-INF\classes\logback-test.xml
        log.info("{}", context.getContextPath());                // /lishuoboy_javaweb_war_exploded
        log.info("{}", context.getContext(""));                  // null
        log.info("{}", context.getMimeType("aaa.jpg"));          // image/jpeg
        log.info("{}min", context.getSessionTimeout());          // 30min
        log.info("{}", context.getServerInfo());                 // Apache Tomcat/9.0.52
        log.info("{}", context.getVirtualServerName());          // Catalina/localhost
        log.info("{}", context.getServletContextName());         // null
        log.info("{}", context.getResponseCharacterEncoding());  // null
        log.info("{}", context.getServletRegistrations());       // {default=org.apache.catalina.core.ApplicationServletRegistration@13ad2636, A01Servlet=org.apache.catalina.core.ApplicationServletRegistration@2320738a, A02Servlet=org.apache.catalina.core.ApplicationServletRegistration@1279988c, jsp=org.apache.catalina.core.ApplicationServletRegistration@7d3b065d, TestAjaxServlet=org.apache.catalina.core.ApplicationServletRegistration@7dd035a, helloServlet=org.apache.catalina.core.ApplicationServletRegistration@27c19c08}
        log.info("{}", context.getDefaultSessionTrackingModes());// [COOKIE, URL]

        log.warn("==context 属性（四个作用域之一）信息====================================");
        Enumeration<String> ctxAttributeNames = context.getAttributeNames();
        while (ctxAttributeNames.hasMoreElements()) {
            String ctxAttributeName = ctxAttributeNames.nextElement();
            log.info("{}=={}", ctxAttributeName, context.getAttribute(ctxAttributeName));
        }

        log.warn("==context 初始参数信息====================================");
        Enumeration<String> ctxInitParameterNames = context.getInitParameterNames();
        while (ctxInitParameterNames.hasMoreElements()) {
            String initParameterName = ctxInitParameterNames.nextElement();
            log.info("{}=={}", initParameterName, context.getInitParameter(initParameterName));
        }

        log.warn("==servlet 初始参数信息====================================");
        Enumeration<String> reqInitParameterNames = getInitParameterNames();
        while (reqInitParameterNames.hasMoreElements()) {
            String initParameterName = reqInitParameterNames.nextElement();
            log.info("{}=={}", initParameterName, getInitParameter(initParameterName));
        }

        request.setAttribute("attr1", "attr1");
        session.setAttribute("attr2", "attr2");
        context.setAttribute("attr3", "attr3");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

    }
}
